﻿using System;
using System.Data;
using System.Windows.Forms;
using SdmxMl.Multiplexor;

namespace SdmxMl.Panels
{
    /// <summary> Dialog for defining Repository proxy </summary>
    public partial class DlgTinyRegistryConfig : Form
    {
        #region Internal Members

        private bool inBinding;

        #endregion

        public string GroupId { get; private set; }

        #region Constructor

        public DlgTinyRegistryConfig()
        {
            InitializeComponent();
            GroupId = string.Empty;
            // Reserve these buttons usage to administrators
            buttonReset.Enabled = Mux.Instance.UserIsAdmin;

            UpdateScreen();
        }
        #endregion

        #region Screen controls update

        private void UpdateScreen()
        {
            using (new SdmxMl.Helper.CWaitCursor())
            {
                textBoxUrl.Text = Mux.Instance.DirInfoProxy.Url;
                buttonImgStatus.Image = imageListState.Images[(int)Mux.Instance.DirInfoProxy.State];
                labelStatusText.Text = Mux.Instance.DirInfoProxy.State.ToString();
                inBinding = true;


                // For multiplexed registry, provides a table with groupID and group text

                multiColumnComboUrl.DataSource = Mux.Instance.ConfigMultiplexed ?
                    Mux.Instance.TableGroups : Mux.Instance.TableRegistry;
             
                // Hide Urn column for multiplexed by giving a size of one
                multiColumnComboUrl.ColumnWidths = Mux.Instance.ConfigMultiplexed ?
                    "100" + ";1;" + (multiColumnComboUrl.Width + 20).ToString() :
                    "100" + (multiColumnComboUrl.Width + 20).ToString();

                if (textBoxUrl.Text.Length > 0)
                    multiColumnComboUrl.Text = textBoxUrl.Text;
                else
                    multiColumnComboUrl.Text = string.Empty;

                inBinding = false;

                textBoxUsage.Text = Mux.Instance.DirInfoRegistryAlias;
            }
        }
        #endregion

        #region button Events

        /// <summary>Recreate new instance of proxy</summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void buttonReloadCfg_Click(object sender, EventArgs e)
        {
            try
            {
                buttonImgStatus.Image = imageListState.Images[3];
                labelStatusText.Text = string.Empty;
                this.Refresh();
                using (new SdmxMl.Helper.CWaitCursor())
                {
                    Mux.CreateNewInstance();
                    UpdateScreen();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>Reset proxy in single mode. Restart and set </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonReset_Click(object sender, EventArgs e)
        {
            try
            {
                buttonImgStatus.Image = imageListState.Images[3];
                labelStatusText.Text = string.Empty;
                this.Refresh();
                using (new SdmxMl.Helper.CWaitCursor())
                {
                    bool foundInList = false;
                    if (Mux.Instance.ConfigMultiplexed)
                    {
                        DataTable dt = (DataTable)multiColumnComboUrl.DataSource;
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            foreach (DataRow row in dt.Rows)
                                if (row["Url"].ToString() == textBoxUrl.Text.Trim().ToLower())
                                {
                                    // Admin reg is first one
                                    Mux.CreateNewInstance(dt.Rows[0]["Url"].ToString());
                                    foundInList = true;
                                    break;
                                }
                        }
                    }

                    // Single mode (or unknown reg)
                    if (foundInList == false)
                        Mux.CreateNewInstance(textBoxUrl.Text.Trim().ToLower());

                    UpdateScreen();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region Multi Combo events

        /// <summary>Redefines registry to use in registry list </summary>
        /// <param name="sender"></param><param name="e"></param>
        private void multiColumnComboUrl_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!inBinding && multiColumnComboUrl.SelectedIndex >= 0)
            {
                DataTable dt = (DataTable)multiColumnComboUrl.DataSource;
                if (dt != null && dt.Rows.Count > multiColumnComboUrl.SelectedIndex)
                {
                    if (Mux.Instance.State == MultiplexorState.OkSingle)
                    {
                        textBoxUrl.Text = dt.Rows[multiColumnComboUrl.SelectedIndex][1].ToString();
                        buttonReset_Click(this, EventArgs.Empty);
                    }
                    else if (Mux.Instance.State == MultiplexorState.OkMultiplex)
                    {
                        // In multiplexor mode, defines what registry is used for DirInfo dialog box
                        Mux.Instance.SetDirInfoProxy(dt.Rows[multiColumnComboUrl.SelectedIndex][1].ToString());
                        GroupId = dt.Rows[multiColumnComboUrl.SelectedIndex][0].ToString();

                        UpdateScreen();
                    }
               }
            }
        }
        #endregion
    }
}
